package com.xneure.database.dialect;

import java.util.Date;
import com.xneure.utils.DateUtil;
import com.xneure.utils.StrUtil;

public class SqlServerDialect extends SqlDialect{
	public SqlServerDialect(){
	}

	@Override
	public String joint(String... str){
		return "CONCAT(".concat(StrUtil.join(str,","));
	}

	@Override
	public String paging(String sql,int start,int end){
		StringBuilder sb = new StringBuilder(sql);
		int select = sb.indexOf("select");
		sb.insert(select + 6," TOP %2s");
		sb.insert(0,"select TOP %1s * from (");
		sb.insert(sb.length(),") tmp_ ");
		int orderBy = sql.lastIndexOf("order by");
		String[] st = sql.substring(orderBy + 9).split("\\s|,");
		sb.append("order by");
		for(String tmp:st){
			sb.append(" ");
			if(tmp.length() < 5 && tmp.length() > 2){
				if(tmp.equalsIgnoreCase("desc")){
					tmp = "ASC,";
				}else if(tmp.equalsIgnoreCase("asc")){
					tmp = "DESC,";
				}
			}
			sb.append(tmp);
		}
		sb.setLength(sb.length() - 1);
		return String.format(sb.toString(),end,end + start);
	}

	@Override
	public String toDate(Object _value){
		return "cast('" + DateUtil.dateFormat((Date)_value) + "' as datetime)";
	}

	@Override
	public String toTimestamp(Object _value){
		throw new RuntimeException("Timestamp 不支持的写入操作。");
	}
}
